package com.zsc.shixun.controller;

import com.zsc.shixun.common.CommonResult;
import com.zsc.shixun.common.ResultCode;
import com.zsc.shixun.common.ResultUtil;
import com.zsc.shixun.model.usermanage.UserManageCreateVO;
import com.zsc.shixun.model.usermanage.UserManageUpdateVO;
import com.zsc.shixun.service.IUserService;
import com.zsc.shixun.utils.LoginMessageUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;

/**
 * <p>
 * 用户管理
 * </p>
 *
 * @author ZWYZY
 * @since 2020/6/7
 */
@Controller
@Validated
@RequestMapping("/userManage")
public class UserManageController {
    private static final Logger logger = LoggerFactory.getLogger(UserManageController.class);

    @Autowired
    private IUserService userService;

    @Autowired
    private LoginMessageUtils loginMessageUtils;

    @RequestMapping("/index")
    public String index(HttpServletRequest request) {
        request.setAttribute("articleVO", userService.getById());
        return "admin/usermanage/index";
    }

    /**
     * 获取用户列表
     *
     * @return
     */
    @GetMapping("/list")
    @ResponseBody
    @Secured("ROLE_user_manage_select")
    public CommonResult getData() {
        return ResultUtil.success(userService.getById());
    }

    /**
     * 修改用户信息
     *
     * @param userManageUpdateVO
     * @return
     */
    @PostMapping("/update")
    @ResponseBody
    @Secured("ROLE_user_manage_update")
    public CommonResult update(@Validated @ModelAttribute UserManageUpdateVO userManageUpdateVO) {
        userService.update(userManageUpdateVO);
        return ResultUtil.success("修改用户成功哦，亲");
    }

    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    @GetMapping("/delete")
    @ResponseBody
    @Secured("ROLE_user_manage_delete")
    public CommonResult delete(@NotNull(message = "id不能为空") @RequestParam(required = false) Long id) {
        if (id.equals(loginMessageUtils.getMessage().getLoginUser().getId())) {
            return new CommonResult(ResultCode.USER_DELETE_YOURSELF_FAIL);
        }
        userService.delete(id);
        return ResultUtil.success("删除用户成功哦，亲");
    }

    /**
     * 新增管理员
     *
     * @param userManageCreateVO
     * @return
     */
    @PostMapping("/insert")
    @ResponseBody
    @Secured("ROLE_user_manage_insert")
    public CommonResult insert(@Validated @ModelAttribute UserManageCreateVO userManageCreateVO) {
        userService.insert(userManageCreateVO);
        return ResultUtil.success("创建管理员成功哦，亲");
    }
}
